<template>
  <view class="min-h-screen w-full max-w-[750rpx] bg-[#e7e7e7] mx-auto">
    <backView />

    <!-- 页面标题 -->
    <view class="bg-[#27c530] text-white p-[30rpx] rounded-b-[20rpx]">
      <text class="text-[32rpx] font-bold text-center block">{{ pageTitle }}</text>
    </view>

    <view class="p-[24rpx] pb-[120rpx]">
      <!-- 全面健康评估 -->
      <view v-if="formType === 'allCareAssessment'" class="space-y-[24rpx]">
        <!-- 1. 疾病与病症 -->
        <view class="form-section">
          <view class="section-header" @click="toggleCollapse('diseaseSymptoms')">
            <text class="section-title">1. 疾病与病症</text>
            <IconFont 
              :name="collapseStates.diseaseSymptoms ? 'arrow-up' : 'arrow-down'" 
              size="12" 
              color="#8bc34a" 
              :class="['transition-transform duration-200', collapseStates.diseaseSymptoms ? 'rotate-180' : 'rotate-0']"
            />
          </view>
          <view v-show="collapseStates.diseaseSymptoms" class="section-content space-y-[16rpx]">
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.diseaseSymptoms?.description || '',
                images: formData?.comprehensiveHealthAssessment?.diseaseSymptoms?.images || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.diseaseSymptoms.description', data.description);
                if (data.images && data.images.length > 0) {
                  updateField('comprehensiveHealthAssessment.diseaseSymptoms.images', data.images);
                }
              }"
              :show-title="false"
              description-label="疾病与病症描述"
              description-placeholder="请输入疾病与病症相关内容"
              :description-rows="4"
              border-color="border-red-300"
            />
            
            <!-- 新增项目 -->
            <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
              <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增项目</text>
              <ItemWithImagesCard
                v-for="(_item, index) in formData?.comprehensiveHealthAssessment?.diseaseSymptoms?.newItems"
                :key="index"
                v-model="formData.comprehensiveHealthAssessment.diseaseSymptoms.newItems[index]"
                :show-delete="true"
                title-label="项目名称"
                description-label="项目描述"
                :description-rows="2"
                border-color="border-red-300"
                @delete="removeNewItem('comprehensiveHealthAssessment.diseaseSymptoms.newItems', index)"
                class="mb-[16rpx]"
              />
              <nut-button type="success" size="small" @click="addNewItem('comprehensiveHealthAssessment.diseaseSymptoms.newItems')" class="w-full"> 添加新项目 </nut-button>
            </view>
          </view>
        </view>

        <!-- 2. 整体健康状况 -->
        <view class="form-section">
          <view class="section-header" @click="toggleCollapse('generalHealthStatus')">
            <text class="section-title">2. 整体健康状况</text>
            <IconFont 
              :name="collapseStates.generalHealthStatus ? 'arrow-up' : 'arrow-down'" 
              size="12" 
              color="#8bc34a" 
              :class="['transition-transform duration-200', collapseStates.generalHealthStatus ? 'rotate-180' : 'rotate-0']"
            />
          </view>
          <view v-show="collapseStates.generalHealthStatus" class="section-content space-y-[16rpx]">
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.generalHealthStatus?.description || '',
                images: formData?.comprehensiveHealthAssessment?.generalHealthStatus?.images || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.generalHealthStatus.description', data.description);
                if (data.images && data.images.length > 0) {
                  updateField('comprehensiveHealthAssessment.generalHealthStatus.images', data.images);
                }
              }"
              :show-title="false"
              description-label="整体健康状况描述"
              description-placeholder="请输入整体健康状况相关内容"
              :description-rows="4"
              border-color="border-blue-300"
            />
            
            <!-- 新增项目 -->
            <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
              <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增项目</text>
              <ItemWithImagesCard
                v-for="(_item, index) in formData?.comprehensiveHealthAssessment?.generalHealthStatus?.newItems"
                :key="index"
                v-model="formData.comprehensiveHealthAssessment.generalHealthStatus.newItems[index]"
                :show-delete="true"
                title-label="项目名称"
                description-label="项目描述"
                :description-rows="2"
                border-color="border-blue-300"
                @delete="removeNewItem('comprehensiveHealthAssessment.generalHealthStatus.newItems', index)"
                class="mb-[16rpx]"
              />
              <nut-button type="success" size="small" @click="addNewItem('comprehensiveHealthAssessment.generalHealthStatus.newItems')" class="w-full"> 添加新项目 </nut-button>
            </view>
          </view>
        </view>

        <!-- 3. 体格检查与生理功能 -->
        <view class="form-section">
          <view class="section-header" @click="toggleCollapse('physicalExamination')">
            <text class="section-title">3. 体格检查与生理功能</text>
            <IconFont 
              :name="collapseStates.physicalExamination ? 'arrow-up' : 'arrow-down'" 
              size="12" 
              color="#8bc34a" 
              :class="['transition-transform duration-200', collapseStates.physicalExamination ? 'rotate-180' : 'rotate-0']"
            />
          </view>
          <view v-show="collapseStates.physicalExamination" class="section-content space-y-[16rpx]">
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.physicalExamination?.description || '',
                images: formData?.comprehensiveHealthAssessment?.physicalExamination?.images || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.physicalExamination.description', data.description);
                if (data.images && data.images.length > 0) {
                  updateField('comprehensiveHealthAssessment.physicalExamination.images', data.images);
                }
              }"
              :show-title="false"
              description-label="体格检查与生理功能描述"
              description-placeholder="请输入体格检查与生理功能相关内容"
              :description-rows="4"
              border-color="border-green-300"
            />
            
            <!-- 新增项目 -->
            <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
              <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增项目</text>
              <ItemWithImagesCard
                v-for="(_item, index) in formData?.comprehensiveHealthAssessment?.physicalExamination?.newItems"
                :key="index"
                v-model="formData.comprehensiveHealthAssessment.physicalExamination.newItems[index]"
                :show-delete="true"
                title-label="项目名称"
                description-label="项目描述"
                :description-rows="2"
                border-color="border-green-300"
                @delete="removeNewItem('comprehensiveHealthAssessment.physicalExamination.newItems', index)"
                class="mb-[16rpx]"
              />
              <nut-button type="success" size="small" @click="addNewItem('comprehensiveHealthAssessment.physicalExamination.newItems')" class="w-full"> 添加新项目 </nut-button>
            </view>
          </view>
        </view>

        <!-- 4. 自理能力 -->
        <view class="form-section">
          <view class="section-header" @click="toggleCollapse('selfCareAbility')">
            <text class="section-title">4. 自理能力</text>
            <IconFont 
              :name="collapseStates.selfCareAbility ? 'arrow-up' : 'arrow-down'" 
              size="12" 
              color="#8bc34a" 
              :class="['transition-transform duration-200', collapseStates.selfCareAbility ? 'rotate-180' : 'rotate-0']"
            />
          </view>
          <view v-show="collapseStates.selfCareAbility" class="section-content space-y-[16rpx]">
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.selfCareAbility?.description || '',
                images: formData?.comprehensiveHealthAssessment?.selfCareAbility?.images || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.selfCareAbility.description', data.description);
                if (data.images && data.images.length > 0) {
                  updateField('comprehensiveHealthAssessment.selfCareAbility.images', data.images);
                }
              }"
              :show-title="false"
              description-label="自理能力描述"
              description-placeholder="请输入自理能力相关内容"
              :description-rows="4"
              border-color="border-yellow-300"
            />
            
            <!-- 新增项目 -->
            <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
              <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增项目</text>
              <ItemWithImagesCard
                v-for="(_item, index) in formData?.comprehensiveHealthAssessment?.selfCareAbility?.newItems"
                :key="index"
                v-model="formData.comprehensiveHealthAssessment.selfCareAbility.newItems[index]"
                :show-delete="true"
                title-label="项目名称"
                description-label="项目描述"
                :description-rows="2"
                border-color="border-yellow-300"
                @delete="removeNewItem('comprehensiveHealthAssessment.selfCareAbility.newItems', index)"
                class="mb-[16rpx]"
              />
              <nut-button type="success" size="small" @click="addNewItem('comprehensiveHealthAssessment.selfCareAbility.newItems')" class="w-full"> 添加新项目 </nut-button>
            </view>
          </view>
        </view>

        <!-- 5. 并发症与风险 -->
        <view class="form-section">
          <view class="section-header" @click="toggleCollapse('complicationsAndRisks')">
            <text class="section-title">5. 并发症与风险</text>
            <IconFont 
              :name="collapseStates.complicationsAndRisks ? 'arrow-up' : 'arrow-down'" 
              size="12" 
              color="#8bc34a" 
              :class="['transition-transform duration-200', collapseStates.complicationsAndRisks ? 'rotate-180' : 'rotate-0']"
            />
          </view>
          <view v-show="collapseStates.physiologicalFunction" class="p-[24rpx] space-y-[32rpx] transition-all duration-300">
            <!-- 循环显示每个生理功能项目 -->
            <view v-for="entry in physiologicalFunctionEntries" :key="entry[0]" class="mb-[16rpx]">
              <view class="mb-[8rpx]">
                <text class="text-[26rpx] font-bold text-gray-800">{{ (entry[1] as any)?.title || getFunctionTitle(entry[0]) }}</text>
              </view>
              <ItemWithImagesCard
                :model-value="{
                  title: '',
                  description: (entry[1] as any)?.description || '',
                  images: (entry[1] as any)?.images || []
                }"
                @update:model-value="(data) => {
                  updateField(`comprehensiveHealthAssessment.allCareAssessment.physiologicalFunction.${entry[0]}.description`, data.description);
                  if (data.images && data.images.length > 0) {
                    updateField(`comprehensiveHealthAssessment.allCareAssessment.physiologicalFunction.${entry[0]}.images`, data.images);
                  }
                }"
                :show-title="false"
                description-label=""
                :description-placeholder="getFunctionPlaceholder(entry[0])"
                :description-rows="3"
                border-color="border-green-300"
              />
            </view>

            <!-- 新增项目 -->
            <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
              <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增项目</text>
              <ItemWithImagesCard
                v-for="(_item, index) in formData?.comprehensiveHealthAssessment?.allCareAssessment.physiologicalFunction.newItems"
                :key="index"
                v-model="formData.comprehensiveHealthAssessment.allCareAssessment.physiologicalFunction.newItems[index]"
                :show-delete="true"
                title-label="项目名称"
                description-label="项目描述"
                :description-rows="2"
                border-color="border-green-300"
                @delete="removeNewItem('physiologicalFunction.newItems', index)"
                class="mb-[16rpx]"
              />
              <nut-button type="success" size="small" @click="addNewItem('physiologicalFunction.newItems')" class="w-full"> 添加新项目 </nut-button>
            </view>

            <!-- 多图片上传区域 -->

          </view>
        </view>

        <!-- 自理能力 -->
        <view class="form-section">
          <view class="section-header" @click="toggleCollapse('ICFSelfCareAbility')">
            <text class="section-title">自理能力</text>
            <IconFont 
              :name="collapseStates.ICFSelfCareAbility ? 'arrow-up' : 'arrow-down'" 
              size="12" 
              color="#8bc34a" 
              :class="['transition-transform duration-200', collapseStates.ICFSelfCareAbility ? 'rotate-180' : 'rotate-0']"
            />
          </view>
          <view v-show="collapseStates.ICFSelfCareAbility" class="section-content space-y-[24rpx]">
            <!-- 认知功能 -->
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.cognitiveFunction || '',
                images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.cognitiveFunctionImages || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.cognitiveFunction', data.description);
                if (data.images && data.images.length > 0) updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.cognitiveFunctionImages', data.images);
              }"
              :show-title="false"
              description-label="认知功能"
              description-placeholder="请输入认知功能情况"
              :description-rows="2"
              border-color="border-blue-300"
            />
            
            <!-- 进食与吞咽障碍 -->
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.eatingSwallowingDisorder || '',
                images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.eatingSwallowingDisorderImages || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.eatingSwallowingDisorder', data.description);
                if (data.images && data.images.length > 0) updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.eatingSwallowingDisorderImages', data.images);
              }"
              :show-title="false"
              description-label="进食与吞咽障碍"
              description-placeholder="请输入进食与吞咽障碍情况"
              :description-rows="2"
              border-color="border-orange-300"
            />
            
            <!-- 排尿功能 -->
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.urinationFunction || '',
                images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.urinationFunctionImages || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.urinationFunction', data.description);
                if (data.images && data.images.length > 0) updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.urinationFunctionImages', data.images);
              }"
              :show-title="false"
              description-label="排尿功能"
              description-placeholder="请输入排尿功能情况"
              :description-rows="2"
              border-color="border-yellow-300"
            />
            
            <!-- 排便功能 -->
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.defecationFunction || '',
                images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.defecationFunctionImages || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.defecationFunction', data.description);
                if (data.images && data.images.length > 0) updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.defecationFunctionImages', data.images);
              }"
              :show-title="false"
              description-label="排便功能"
              description-placeholder="请输入排便功能情况"
              :description-rows="2"
              border-color="border-yellow-300"
            />
            
            <!-- 身体约束 -->
            <ItemWithImagesCard
              :model-value="{
                title: '',
                description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.physicalRestraint || '',
                images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.ICFSelfCareAbility?.physicalRestraintImages || []
              }"
              @update:model-value="(data) => {
                updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.physicalRestraint', data.description);
                if (data.images && data.images.length > 0) updateField('comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.physicalRestraintImages', data.images);
              }"
              :show-title="false"
              description-label="身体约束"
              description-placeholder="请输入身体约束情况"
              :description-rows="2"
              border-color="border-red-300"
            />

            <!-- 新增项目 -->
            <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
              <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增项目</text>
              <ItemWithImagesCard
                v-for="(_item, index) in formData?.comprehensiveHealthAssessment?.allCareAssessment.ICFSelfCareAbility.newItems"
                :key="index"
                v-model="formData.comprehensiveHealthAssessment.allCareAssessment.ICFSelfCareAbility.newItems[index]"
                :show-delete="true"
                title-label="项目名称"
                description-label="项目描述"
                :description-rows="2"
                border-color="border-yellow-300"
                @delete="removeNewItem('ICFSelfCareAbility.newItems', index)"
                class="mb-[16rpx]"
              />
              <nut-button type="success" size="small" @click="addNewItem('ICFSelfCareAbility.newItems')" class="w-full"> 添加新项目 </nut-button>
            </view>
          </view>
        </view>

        <!-- 并发症与风险 -->
        <view class="form-section">
          <view class="section-header" @click="toggleCollapse('risksAndComplications')">
            <text class="section-title">并发症与风险</text>
            <IconFont 
              :name="collapseStates.risksAndComplications ? 'arrow-up' : 'arrow-down'" 
              size="12" 
              color="#8bc34a" 
              :class="['transition-transform duration-200', collapseStates.risksAndComplications ? 'rotate-180' : 'rotate-0']"
            />
          </view>
          <view v-show="collapseStates.risksAndComplications" class="section-content space-y-[24rpx]">
            <!-- 压力性损伤风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.pressureInjuryRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.pressureInjuryRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.pressureInjuryRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.pressureInjuryRiskImages', data.images); }"
              :show-title="false" description-label="压力性损伤（压疮）风险评估" description-placeholder="请输入压力性损伤风险评估" :description-rows="2" border-color="border-red-300"
            />
            <!-- 跌倒风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.fallRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.fallRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.fallRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.fallRiskImages', data.images); }"
              :show-title="false" description-label="跌倒(坠床)风险评估" description-placeholder="请输入跌倒风险评估" :description-rows="2" border-color="border-orange-300"
            />
            <!-- 营养风险筛查 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.nutritionRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.nutritionRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.nutritionRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.nutritionRiskImages', data.images); }"
              :show-title="false" description-label="营养风险筛查" description-placeholder="请输入营养风险筛查" :description-rows="2" border-color="border-green-300"
            />
            <!-- 吞咽障碍风险筛查 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.swallowingDisorderRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.swallowingDisorderRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.swallowingDisorderRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.swallowingDisorderRiskImages', data.images); }"
              :show-title="false" description-label="吞咽障碍风险筛查" description-placeholder="请输入吞咽障碍风险筛查" :description-rows="2" border-color="border-yellow-300"
            />
            <!-- 深静脉血栓风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.deepVeinThrombosisRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.deepVeinThrombosisRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.deepVeinThrombosisRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.deepVeinThrombosisRiskImages', data.images); }"
              :show-title="false" description-label="深静脉血栓风险评估" description-placeholder="请输入深静脉血栓风险评估" :description-rows="2" border-color="border-purple-300"
            />
            <!-- 肺血栓栓塞症风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.pulmonaryEmbolismRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.pulmonaryEmbolismRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.pulmonaryEmbolismRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.pulmonaryEmbolismRiskImages', data.images); }"
              :show-title="false" description-label="肺血栓栓塞症风险评估" description-placeholder="请输入肺血栓栓塞症风险评估" :description-rows="2" border-color="border-indigo-300"
            />
            <!-- 非计划性拔管风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.unplannedExtubationRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.unplannedExtubationRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.unplannedExtubationRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.unplannedExtubationRiskImages', data.images); }"
              :show-title="false" description-label="非计划性拔管风险评估" description-placeholder="请输入非计划性拔管风险评估" :description-rows="2" border-color="border-pink-300"
            />
            <!-- 自杀风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.suicideRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.suicideRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.suicideRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.suicideRiskImages', data.images); }"
              :show-title="false" description-label="自杀风险评估" description-placeholder="请输入自杀风险评估" :description-rows="2" border-color="border-gray-400"
            />
            <!-- 卒中风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.strokeRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.strokeRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.strokeRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.strokeRiskImages', data.images); }"
              :show-title="false" description-label="卒中风险评估" description-placeholder="请输入卒中风险评估" :description-rows="2" border-color="border-blue-300"
            />
            <!-- 感染风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.infectionRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.infectionRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.infectionRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.infectionRiskImages', data.images); }"
              :show-title="false" description-label="感染风险评估" description-placeholder="请输入感染风险评估" :description-rows="2" border-color="border-cyan-300"
            />
            <!-- 低血糖风险评估 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.hypoglycemiaRisk || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.hypoglycemiaRiskImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.hypoglycemiaRisk', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.hypoglycemiaRiskImages', data.images); }"
              :show-title="false" description-label="低血糖风险评估" description-placeholder="请输入低血糖风险评估" :description-rows="2" border-color="border-yellow-300"
            />
            <!-- 早期预警评分 -->
            <ItemWithImagesCard
              :model-value="{title: '', description: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.earlyWarningScore || '', images: formData?.comprehensiveHealthAssessment?.allCareAssessment?.risksAndComplications?.earlyWarningScoreImages || []}"
              @update:model-value="(data) => { updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.earlyWarningScore', data.description); if (data.images?.length) updateField('comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.earlyWarningScoreImages', data.images); }"
              :show-title="false" description-label="早期预警评分" description-placeholder="请输入早期预警评分" :description-rows="2" border-color="border-teal-300"
            />

            <!-- 新增项目 -->
            <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
              <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增项目</text>
              <ItemWithImagesCard
                v-for="(_item, index) in formData?.comprehensiveHealthAssessment?.allCareAssessment.risksAndComplications.newItems"
                :key="index"
                v-model="formData.comprehensiveHealthAssessment.allCareAssessment.risksAndComplications.newItems[index]"
                :show-delete="true"
                title-label="项目名称"
                description-label="项目描述"
                :description-rows="2"
                border-color="border-red-300"
                @delete="removeNewItem('risksAndComplications.newItems', index)"
                class="mb-[16rpx]"
              />
              <nut-button type="success" size="small" @click="addNewItem('risksAndComplications.newItems')" class="w-full"> 添加新项目 </nut-button>
            </view>
          </view>
        </view>

        <!-- 其他评估项目 -->
        <view class="form-section">
          <view class="section-header" @click="toggleCollapse('otherAssessment')">
            <text class="section-title">其他评估项目</text>
            <IconFont 
              :name="collapseStates.otherAssessment ? 'arrow-up' : 'arrow-down'" 
              size="12" 
              color="#8bc34a" 
              :class="['transition-transform duration-200', collapseStates.otherAssessment ? 'rotate-180' : 'rotate-0']"
            />
          </view>
          <view v-show="collapseStates.otherAssessment" class="section-content space-y-[24rpx]">
            <view>
              <text class="form-label">主要护理诊断/健康问题</text>
              <nut-textarea :model-value="formData?.comprehensiveHealthAssessment?.allCareAssessment?.nursingDiagnosis || ''" @update:model-value="updateField('comprehensiveHealthAssessment.allCareAssessment.nursingDiagnosis', $event)" placeholder="请输入主要护理诊断/健康问题" :rows="3" class="w-full" />
            </view>
            <view>
              <text class="form-label">初步护理计划</text>
              <nut-textarea :model-value="formData?.comprehensiveHealthAssessment?.allCareAssessment?.preliminaryNursingPlan || ''" @update:model-value="updateField('comprehensiveHealthAssessment.allCareAssessment.preliminaryNursingPlan', $event)" placeholder="请输入初步护理计划" :rows="3" class="w-full" />
            </view>
            <view>
              <text class="form-label">记录与签名</text>
              <nut-textarea :model-value="formData?.comprehensiveHealthAssessment?.allCareAssessment?.recordingAndSignatures || ''" @update:model-value="updateField('comprehensiveHealthAssessment.allCareAssessment.recordingAndSignatures', $event)" placeholder="请输入记录与签名" :rows="3" class="w-full" />
            </view>
            <view>
              <text class="form-label">评估量表</text>
              <nut-textarea :model-value="formData?.comprehensiveHealthAssessment?.allCareAssessment?.assessmentScales || ''" @update:model-value="updateField('comprehensiveHealthAssessment.allCareAssessment.assessmentScales', $event)" placeholder="请输入评估量表" :rows="3" class="w-full" />
            </view>
            <view>
              <text class="form-label">文档说明</text>
              <nut-textarea :model-value="formData?.comprehensiveHealthAssessment?.allCareAssessment?.documentDescription || ''" @update:model-value="updateField('comprehensiveHealthAssessment.allCareAssessment.documentDescription', $event)" placeholder="请输入文档说明" :rows="3" class="w-full" />
            </view>
          </view>
        </view>
      </view>

      <!-- 居家护理专项评估 -->
      <view v-else-if="formType === 'homeCareAssessment'" class="form-section">
        <view class="section-header" @click="toggleCollapse('homeCareAssessment')">
          <text class="section-title">居家护理专项评估</text>
          <IconFont 
            :name="collapseStates.homeCareAssessment ? 'arrow-up' : 'arrow-down'" 
            size="12" 
            color="#8bc34a" 
            :class="['transition-transform duration-200', collapseStates.homeCareAssessment ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.homeCareAssessment" class="p-[24rpx] transition-all duration-300">
          <nut-textarea :model-value="formData?.comprehensiveHealthAssessment?.homeCareAssessment || ''" @update:model-value="updateField('comprehensiveHealthAssessment.homeCareAssessment', $event)" placeholder="请输入居家护理专项评估内容" :rows="8" class="w-full" />
        </view>
      </view>

      <!-- 历史健康评估归档 -->
      <view v-else-if="formType === 'historicalHealthAssessments'" class="form-section">
        <view class="section-header" @click="toggleCollapse('historicalHealthAssessments')">
          <text class="section-title">历史健康评估归档</text>
          <IconFont 
            :name="collapseStates.historicalHealthAssessments ? 'arrow-up' : 'arrow-down'" 
            size="12" 
            color="#8bc34a" 
            :class="['transition-transform duration-200', collapseStates.historicalHealthAssessments ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.historicalHealthAssessments" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <view v-for="(item, index) in formData?.comprehensiveHealthAssessment?.historicalHealthAssessments" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx]">
            <view class="flex justify-between items-center mb-[12rpx]">
              <text class="text-[24rpx] font-medium text-gray-700">评估记录 {{ index + 1 }}</text>
              <nut-button type="danger" size="small" @click="removeHistoricalAssessment(index)">删除</nut-button>
            </view>
            <view class="mb-[12rpx]">
              <text class="text-[20rpx] text-gray-600 block mb-[8rpx]">评估日期</text>
              <nut-input v-model="item.date" placeholder="请输入评估日期" />
            </view>
            <view>
              <text class="text-[20rpx] text-gray-600 block mb-[8rpx]">评估内容</text>
              <nut-textarea v-model="item.assessment" placeholder="请输入评估内容" :rows="3" class="w-full" />
            </view>
          </view>

          <nut-button type="primary" size="large" @click="addHistoricalAssessment" class="w-full"> 添加历史评估记录 </nut-button>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="fixed bottom-0 left-0 right-0 bg-[#e7e7e7] p-[24rpx] border-t border-gray-200">
      <view class="flex gap-[16rpx]">
        <nut-button type="default" @click="goBack" class="flex-1"> 返回 </nut-button>
        <nut-button type="success" @click="saveData" class="flex-1"> 保存 </nut-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import Taro from "@tarojs/taro";
import { useMedicalRecordStore } from "@/store/modules/medicalRecord";
import backView from "@/components/backView.vue";
import ItemWithImagesCard from "@/components/ItemWithImagesCard.vue";
import { IconFont } from '@nutui/icons-vue-taro';

const medicalRecordStore = useMedicalRecordStore();

const formType = ref("");
const idNumber = ref("");
const recordId = ref(""); // 添加记录ID用于保存

// 折叠状态管理
const collapseStates = ref({
  basicIndicators: false,        // 基础指标
  auxiliaryExamination: false,   // 辅助检查
  diseaseSymptoms: false,        // 疾病病症
  generalHealthStatus: false,    // 一般健康状况
  specialistAssessment: false,   // 专科评估
  physiologicalFunction: false,  // 体格检查与生理功能
  ICFSelfCareAbility: false,     // ICF自理能力
  risksAndComplications: false,  // 风险和并发症
  otherAssessment: false,        // 其他评估项目
  homeCareAssessment: false,     // 居家护理专项评估
  historicalHealthAssessments: false // 历史健康评估归档
})

// 切换折叠状态
const toggleCollapse = (section: keyof typeof collapseStates.value) => {
  collapseStates.value[section] = !collapseStates.value[section]
}

const formData:any = computed(() => {
  return medicalRecordStore.getData;
});

const pageTitle = computed(() => {
  switch (formType.value) {
    case "allCareAssessment":
      return "全面健康评估";
    case "homeCareAssessment":
      return "居家护理专项评估";
    case "historicalHealthAssessments":
      return "历史健康评估归档";
    default:
      return "子表单";
  }
});

const physiologicalFunctionEntries = computed(() => {
  try {
    const func = formData.value?.comprehensiveHealthAssessment?.allCareAssessment?.physiologicalFunction;
    console.log("physiologicalFunctionEntries - func:", func);
    if (!func || typeof func !== "object") {
      console.log("physiologicalFunctionEntries - func is null or not object");
      return [];
    }
    const entries = Object.entries(func).filter(([key]) => key !== "newItems");
    console.log("physiologicalFunctionEntries - entries:", entries);
    return entries;
  } catch (error) {
    console.error("Error in physiologicalFunctionEntries:", error);
    return [];
  }
});

/**
 * 获取功能项目的标题
 */
function getFunctionTitle(key: string): string {
  const titleMap: Record<string, string> = {
    // 体格检查与生理功能项目
    'generalExamination': '体格检查一般检查内容',
    'headExamination': '头部检查',
    'chestExamination': '胸部检查',
    'abdominalExamination': '腹部体格检查',
    'analRectalExamination': '肛门与直肠检查',
    'urinarySystemExamination': '泌尿系统检查',
    'nervousSystemExamination': '神经系统检查',
    'jointMobilityExamination': '关节活动度检查',
    'nervousDysfunction': '神经功能障碍',
    'spineSpecialTests': '脊柱特殊试验',
    'textDescription': '文字描述',
    'photos': '照片',
    
    // 其他功能项目
    'cardiovascularFunction': '心血管功能',
    'respiratoryFunction': '呼吸功能', 
    'digestiveFunction': '消化功能',
    'urinaryFunction': '泌尿功能',
    'nervousFunction': '神经系统功能',
    'musculoskeletalFunction': '肌肉骨骼功能',
    'endocrineFunction': '内分泌功能',
    'immuneFunction': '免疫功能',
    'sensoryFunction': '感觉功能',
    'cognitiveFunction': '认知功能',
    'emotionalFunction': '情绪功能',
    'socialFunction': '社会功能',
    'sleepFunction': '睡眠功能',
    'nutritionFunction': '营养功能',
    'mobilityFunction': '活动功能',
    'safetyFunction': '安全功能',
    'painFunction': '疼痛评估',
    'skinFunction': '皮肤功能',
    'woundFunction': '伤口评估',
    'medicationFunction': '用药功能'
  };
  return titleMap[key] || key;
}

/**
 * 获取功能项目的占位符
 */
function getFunctionPlaceholder(key: string): string {
  const placeholderMap: Record<string, string> = {
    // 体格检查与生理功能项目
    'generalExamination': '请描述一般体格检查情况，包括生命体征、一般状况等',
    'headExamination': '请描述头部检查情况，包括头颅、面部、眼耳鼻喉等',
    'chestExamination': '请描述胸部检查情况，包括心肺听诊、胸廓形态等',
    'abdominalExamination': '请描述腹部体格检查情况，包括腹部触诊、叩诊、听诊等',
    'analRectalExamination': '请描述肛门与直肠检查情况，包括肛门指检、直肠镜检查等',
    'urinarySystemExamination': '请描述泌尿系统检查情况，包括肾脏、膀胱、尿道等',
    'nervousSystemExamination': '请描述神经系统检查情况，包括神经反射、肌力、感觉等',
    'jointMobilityExamination': '请描述关节活动度检查情况，包括各关节活动范围、稳定性等',
    'nervousDysfunction': '请描述神经功能障碍情况，包括运动、感觉、自主神经功能等',
    'spineSpecialTests': '请描述脊柱特殊试验情况，包括各种特殊检查方法等',
    'textDescription': '请输入文字描述内容',
    'photos': '请上传相关照片',
    
    // 其他功能项目
    'cardiovascularFunction': '请描述心血管功能检查情况，包括心率、血压、心律等',
    'respiratoryFunction': '请描述呼吸功能检查情况，包括呼吸频率、呼吸音、血氧饱和度等',
    'digestiveFunction': '请描述消化功能检查情况，包括食欲、消化、排便等',
    'urinaryFunction': '请描述泌尿功能检查情况，包括排尿、尿液性状等',
    'nervousFunction': '请描述神经系统功能检查情况，包括意识、反应、协调性等',
    'musculoskeletalFunction': '请描述肌肉骨骼功能检查情况，包括肌力、关节活动度等',
    'endocrineFunction': '请描述内分泌功能检查情况，包括血糖、甲状腺功能等',
    'immuneFunction': '请描述免疫功能检查情况，包括抵抗力、感染情况等',
    'sensoryFunction': '请描述感觉功能检查情况，包括视觉、听觉、触觉等',
    'cognitiveFunction': '请描述认知功能检查情况，包括记忆力、注意力、判断力等',
    'emotionalFunction': '请描述情绪功能检查情况，包括情绪状态、心理状态等',
    'socialFunction': '请描述社会功能检查情况，包括社交能力、人际关系等',
    'sleepFunction': '请描述睡眠功能检查情况，包括睡眠质量、睡眠时间等',
    'nutritionFunction': '请描述营养功能检查情况，包括营养状况、饮食情况等',
    'mobilityFunction': '请描述活动功能检查情况，包括行走、转移、平衡等',
    'safetyFunction': '请描述安全功能检查情况，包括跌倒风险、环境安全等',
    'painFunction': '请描述疼痛评估情况，包括疼痛部位、程度、性质等',
    'skinFunction': '请描述皮肤功能检查情况，包括皮肤完整性、颜色、温度等',
    'woundFunction': '请描述伤口评估情况，包括伤口类型、大小、愈合情况等',
    'medicationFunction': '请描述用药功能检查情况，包括用药依从性、不良反应等'
  };
  return placeholderMap[key] || '请输入相关检查描述';
}

/**
 * 更新字段值
 */
function updateField(field: string, value: any) {
  console.log("更新字段:", field, value);
  medicalRecordStore.updateField(field, value);
}

onMounted(async () => {
  const params = Taro.getCurrentInstance().router?.params;
  if (params?.type) {
    formType.value = params.type;
  }
  if (params?.idNumber) {
    idNumber.value = params.idNumber;
  }
  if (params?.id) {
    recordId.value = params.id;
    // 从既往病史记录加载数据
    console.log("开始从既往病史记录加载数据，ID:", params.id);
    const result = await medicalRecordStore.loadFromPastMedicalInfo(params.id);
    console.log("数据加载结果:", result);

    if (!result.success) {
      Taro.showToast({
        title: result?.message || "数据加载失败",
        icon: "none",
        duration: 3000,
      });
    }
  } else {
    // 如果没有记录ID，总是初始化默认数据
    medicalRecordStore.initializeFormData();
  }

  // 等待异步操作完成后再检查数据
  // await new Promise(resolve => setTimeout(resolve, 0));
  
  // 确保 formData 已初始化（仅在确实没有数据时）
  if (!medicalRecordStore.getData) {
    console.log("检测到 formData 为空，重新初始化");
    medicalRecordStore.initializeFormData();
  }

  // Debug: Log the formData structure
  console.log("FormData structure:", formData.value);
  console.log("Physiological function entries:", physiologicalFunctionEntries.value);
});

function addNewItem(path: string) {
  // 确保 formData 已初始化
  if (!medicalRecordStore.getData) {
    medicalRecordStore.initializeFormData();
  }
  
  const newItem: any = { title: "", description: "", images: [] };
  medicalRecordStore.addNewItem(`comprehensiveHealthAssessment.allCareAssessment.${path}`, newItem);
}

function removeNewItem(path: string, index: number) {
  // 确保 formData 已初始化
  if (!medicalRecordStore.getData) {
    medicalRecordStore.initializeFormData();
  }
  
  medicalRecordStore.removeNewItem(`comprehensiveHealthAssessment.allCareAssessment.${path}`, index);
}

function addHistoricalAssessment() {
  // 确保 formData 已初始化
  if (!medicalRecordStore.getData) {
    medicalRecordStore.initializeFormData();
  }
  
  medicalRecordStore.addNewItem("comprehensiveHealthAssessment.historicalHealthAssessments", {
    date: "",
    assessment: "",
  });
}

function removeHistoricalAssessment(index: number) {
  // 确保 formData 已初始化
  if (!medicalRecordStore.getData) {
    medicalRecordStore.initializeFormData();
  }
  
  medicalRecordStore.removeNewItem("comprehensiveHealthAssessment.historicalHealthAssessments", index);
}


async function saveData() {
  try {
    console.log("=== 开始保存数据 ===");
    console.log("recordId.value:", recordId.value);
    console.log("medicalRecordStore.getData:", medicalRecordStore.getData);
    console.log("formData.value:", formData.value);
    console.log("formData.value === medicalRecordStore.getData:", formData.value === medicalRecordStore.getData);
    
    // 如果 formData.value 为空但 store 有数据，强制同步
    if (!formData.value && medicalRecordStore.getData) {
      console.log("检测到数据不同步，强制重新获取");
      // 触发响应式更新
      await new Promise(resolve => setTimeout(resolve, 0));
    }
    
    console.log("保存前的最终数据检查:");
    console.log("formData.value:", formData.value);
    console.log("medicalRecordStore.getData:", medicalRecordStore.getData);

    const result = await medicalRecordStore.saveToPastMedicalInfo(recordId.value);
    console.log("保存结果:", result);

    if (result.success) {
      console.log("保存成功！");
      Taro.showToast({
        title: "保存成功",
        icon: "success",
      });
    } else {
      console.log("保存失败:", result.message);
      Taro.showToast({
        title: result.message,
        icon: "error",
        duration: 3000,
      });
    }
    console.log("=== 保存数据完成 ===");
  } catch (error) {
    console.error("保存数据异常:", error);
    Taro.showToast({
      title: "保存失败",
      icon: "error",
      duration: 3000,
    });
  }
}

function goBack() {
  Taro.navigateBack();
}

</script>

<style scoped lang="scss">
:deep(.nut-textarea) {
  border-radius: 8rpx;
  padding: 12rpx 20rpx;
  background: #f0f0f0;
}

// 图片网格样式
.grid {
  display: grid;
}

.grid-cols-3 {
  grid-template-columns: repeat(3, 1fr);
}

.gap-12rpx {
  gap: 12rpx;
}

// 图片预览样式
.image-preview {
  position: relative;
  display: inline-block;
}

.image-preview .delete-btn {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 32rpx;
  height: 32rpx;
  background-color: #ef4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20rpx;
  cursor: pointer;
}

.image-preview .delete-btn:hover {
  background-color: #dc2626;
}

// 折叠动画样式
.collapse-header {
  cursor: pointer;
  transition: background-color 0.2s ease;
  
  &:hover {
    background-color: #f0f0f0;
  }
  
  &:active {
    background-color: #e0e0e0;
  }
}

// 简化的重复样式类
.section-header {
  background: #f6f6f6;
  padding: 24rpx;
  border-bottom: 1rpx solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  transition: background-color 0.2s ease;
  border-top: solid 6rpx #8BC34A;
  
  &:hover {
    background-color: #f0f0f0;
  }
  
  &:active {
    background-color: #e0e0e0;
  }
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #1f2937;
}

.section-content {
  padding: 24rpx;
  transition: all 0.3s ease;
}

.form-section {
  background: white;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 24rpx;
}

.form-label {
  font-size: 24rpx;
  font-weight: 500;
  color: #374151;
  display: block;
  margin-bottom: 12rpx;
}

.collapse-content {
  overflow: hidden;
  transition: all 0.3s ease;
}

// 箭头旋转动画
.arrow-icon {
  transition: transform 0.2s ease;
}

.arrow-icon.expanded {
  transform: rotate(180deg);
}

// 确保旋转动画平滑
.rotate-0 {
  transform: rotate(0deg);
}

.rotate-180 {
  transform: rotate(180deg);
}
</style>
